<template>
  <view>
    <up-upload :fileList="fileList" :maxCount="maxCount" @afterRead="afterRead" @delete="deletePic" name="1" :uploadText="uploadText"
      :previewFullImage="true" :uploadIcon="uploadIcon"></up-upload>
  </view>
</template>

<script setup>
  import {
    ref,
    defineProps,
    defineEmits
  } from 'vue'
  import {
    env
  } from '@/http/env.js'
  const fileList = ref([]);
  const {
    maxCount,uploadIcon,uploadText,id
  } = defineProps(['maxCount','uploadIcon','uploadText',"id"])
  const emit = defineEmits(['deletePic', 'uploadFile', 'UploadAvatar'])
  // 删除图片
  const deletePic = (event) => {
    fileList.value.splice(event.index, 1);
    emit('deletePic', fileList.value)
  }
  // 新增图片
  const afterRead = async (event) => {
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let lists = [].concat(event.file);
    let fileListLen = fileList.value.length;
    lists.map((item) => {
      fileList.value.push({
        ...item,
        status: 'uploading',
        message: '上传中',
      });
    });
    for (let i = 0; i < lists.length; i++) {
      const result = await uploadFilePromise(lists[i].url);
      let item = fileList.value[fileListLen];
      fileList.value.splice(fileListLen, 1, {
        ...item,
        status: 'success',
        message: '',
        url: result,
      });
      fileListLen++;
    }

    emit('uploadFile', fileList.value)

  }

  const uploadFilePromise = (url) => {
    const token = uni.getStorageSync('userInfo').token
    return new Promise((resolve, reject) => {
      let a = uni.uploadFile({
        url: `${env.baseUrl}/common/upload`, // 本地地址
        // url: 'https://localhost:8080/common/upload', // 测试环境调试
        filePath: url,
        name: 'file',
        formData: {
          user: 'test'
        },
        header: {
          token: token
        },
        success: (res) => {
          setTimeout(() => {
            const data = JSON.parse(res.data)
            if (data && data.code === 1) {
              const avatar = data.data.fullurl
              const val = {url:avatar,id}
              emit("UploadAvatar", val)
            } else {
              uni.showToast({
                title: data.msg,
                icon: "none"
              })
            }
            resolve(data.data.fullurl)
          }, 500)
        }
      });
    })
  }
</script>

<style lang="less">

</style>